//
//  WebserviceManager.m
//  Volatix
//
//  Created by Familly on 6/11/14.
//  Copyright (c) 2014 Familly. All rights reserved.
//

#import "WebserviceManager.h"
//#import "NSDate+Helper.h"

@interface WebserviceManager (local)

// Local business methods
- (NSString *)fullURLRequestWithAPI:(NSString *)strApiUrl;

@end

@implementation WebserviceManager

+ (WebserviceManager *)sharedInstance {
    
    static dispatch_once_t once;
    static WebserviceManager *sharedInstanceObj;
    dispatch_once(&once, ^{
        sharedInstanceObj = [[WebserviceManager alloc] initWithBaseURL:nil];
    });
    
    return sharedInstanceObj;
}
-(instancetype)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (self) {
        self.requestSerializer = [AFJSONRequestSerializer serializer];
        self.responseSerializer = [AFJSONResponseSerializer serializer];
        [self.securityPolicy setAllowInvalidCertificates:NO]; ///ssl
    }
    
    return self;
}
#pragma mark --
#pragma mark - Local business methods

- (NSString *)fullURLRequestWithAPI:(NSString *)strApiUrl {
    
    return [URL_SERVICE stringByAppendingString:strApiUrl];
}

- (NSString *)getAPIPathWithType:(ENUM_API_REQUEST_TYPE)type andParams:(NSMutableDictionary *)params {
    
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
//    NSString* dateString = [dateFormatter stringFromDate:[NSDate date]];
    
    switch (type) {
            
            
        case ENUM_API_REQUEST_UPDATE_DATA_REAL_TIME:
        {
            return UPDATE_DATA_REAL_TIME;
        }
        case ENUM_API_REQUEST_GET_LIST_DYNAMIC_COLUMN:
        {
            return GET_LIST_DYNAMIC_COLUMN;
        }
        case ENUM_API_REQUEST_LIST_ISO:
        {
            NSNumber * pageIndex=[params objectForKey:@"PageIndex"];
            NSNumber * pageSize  =[params objectForKey:@"pageSize"];
            NSString *path = GET_LIST_ISO([pageIndex intValue],[pageSize intValue]);
            NSLog(@"%@",path);
            [params removeAllObjects];
            return path;
        }
        case ENUM_API_REQUEST_LIST_LOADZONE:{
            
            NSNumber * pageIndex=[params objectForKey:@"PageIndex"];
            NSNumber * pageSize  =[params objectForKey:@"pageSize"];
            NSString * ISO =[params objectForKey:@"ISO"];
            NSString *path = GET_LOADZONE([pageIndex intValue],[pageSize intValue],ISO);
            [params removeAllObjects];
            return path;
            
        }
        case ENUM_API_REQUEST_LIST_POWERPOINT:{
            NSNumber * pageIndex=[params objectForKey:@"PageIndex"];
            NSNumber * pageSize  =[params objectForKey:@"pageSize"];
            NSString * ISO =[params objectForKey:@"ISO"];
            NSString * LOADZONE =[params objectForKey:@"LOADZONE"];
            NSString *path = GET_POWERPOINT([pageIndex intValue],[pageSize intValue],ISO,LOADZONE);
            [params removeAllObjects];
            return path;
        }
        case ENUM_API_REQUEST_UPDATE_DATA_DAY_AHEAD:{
             NSString * date=[params objectForKey:@"DATE_TIME"];
             NSString *path = GET_DATA_DAY_AHEAD(date);
            path =[path stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
             [params removeAllObjects];
            return path;
        }
        case ENUM_API_REQUEST_GET_HISTORY:
        {
            int  kind=[[params objectForKey:@"KIND"] intValue];
            NSString * date=[params objectForKey:@"DATE_TIME"];
            NSString *path=@"";
            if(kind==LEVEL_ISO)
            {
                NSString * ISO =[params objectForKey:@"ISO"];
                path = GET_ISO_DAY_AHEAD(date,[ISO lowercaseString]);
            }
            else if(kind== LEVEL_LOADZONE)
            {
                NSString * ISO =[params objectForKey:@"ISO"];
                NSString * LOADZONE =[params objectForKey:@"LOADZONE"];
                path = GET_LOAD_ZONE_DAY_AHEAD(date,[ISO lowercaseString],[LOADZONE lowercaseString]);
                
            }
            else if(kind == LEVEL_POWERPOINT)
            {
                NSString * ISO =[params objectForKey:@"ISO"];
                NSString * LOADZONE =[params objectForKey:@"LOADZONE"];
                NSString * POWERPOINT =[params objectForKey:@"POWERPOINT"];
                path = GET_POWER_POINT_DAY_AHEAD(date,[ISO lowercaseString],[LOADZONE lowercaseString],[POWERPOINT lowercaseString]);
            }
            path =[path stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
            NSLog(@"path %@",path);
           
            [params removeAllObjects];
             return path;
                
        }
            
        case ENUM_API_REQUEST_LOGIN:{
            return LOGIN;
        }
        case ENUM_API_REQUEST_LOGOUT:{
            return LOGOUT;
        }
        /*
        case ENUM_API_REQUEST_GET_TIME_LEFT:
        {
            NSString *path = [NSString stringWithFormat:API_URL_GET_TIME_LEFT, params[@"userID"]];
            [params removeAllObjects];
            return path;
        }
            
        */
            
        default:
            return @"";
    }
}

#pragma mark - OVERRIDE MOTHODS
-(AFHTTPRequestOperation *)POST_ARRAY:(NSString *)URLString parameters:(NSString *)body success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure{
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:10];
    
   
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
     NSLog(@"url  = %@", [request.URL absoluteString]);
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];
    return operation;
    
    
}



-(AFHTTPRequestOperation *)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    // adding auth key
   ////---> [request setValue:[ApplicationDelegate getAuthoToken] forHTTPHeaderField:@"AuthenticationToken"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //    NSLog(@"header = %@", request.allHTTPHeaderFields);
    NSLog(@"url  = %@", [request.URL absoluteString]);
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];
    
    return operation;
}

-(AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
    // adding auth key
    ////--->[request setValue:[ApplicationDelegate getAuthoToken] forHTTPHeaderField:@"AuthenticationToken"];

    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:kAccessToken];
    if(accessToken!=nil){
        [request setValue:[NSString stringWithFormat:@"Bearer %@",accessToken] forHTTPHeaderField:@"Authorization"];
    }
    //////-----> more
    
     NSLog(@"url  = %@", [request.URL absoluteString]);
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];
    
    return operation;
}

-(AFHTTPRequestOperation *)PUT:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PUT" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    
    // adding auth key
    ////--->[request setValue:[ApplicationDelegate getAuthoToken] forHTTPHeaderField:@"AuthenticationToken"];
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];
    
    return operation;
}

-(AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))block success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:nil];
    
    // set timeout for upload task
    [request setTimeoutInterval:5*60];
    // adding auth key
    ////--->[request setValue:/*[ApplicationDelegate getAuthoToken]*/ forHTTPHeaderField:@"AuthenticationToken"];
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];
    
    return operation;
}

#pragma mark --
#pragma mark -  BUSINESS METHODS
- (AFHTTPRequestOperation *)operationWithType:(ENUM_API_REQUEST_TYPE)type
                            andPostMethodKind:(int)methodKind
                                    andParams:(NSMutableDictionary *)params
                                    andString:(NSString *)strBody
                                       inView:(UIView *)view
                                completeBlock:(void (^)(id responseObject))block
                                 failureBlock:(void (^)(NSError *error))failureBlock
{
    return [self operationWithType:type andMethodKind:methodKind andParams:params andString:strBody inView:view completeBlock:block failureBlock:failureBlock];
}

-(AFHTTPRequestOperation *)operationWithType:(ENUM_API_REQUEST_TYPE)type andMethodKind:(enumAPIRequestMethodKind)methodKind andParams:(NSMutableDictionary *)params andString:(NSString *)strBody inView:(UIView *)view completeBlock:(void (^)(id))block failureBlock:(void (^)(NSError *))failureBlock
{
    
    NSString *path = [self getAPIPathWithType:type andParams:params];
    if (!path || [path length] == 0) {
        return nil;
    }
    
    // get full path
    path = [self fullURLRequestWithAPI:path];
    if ([params count] == 0) {
        params = nil;
    }
    //NSLog(@"%@", path);
    //NSLog(@"param = %@", params);
    
    AFHTTPRequestOperation *op;
    if (methodKind == enumAPIRequestMethod_POST) { // POST
        if (view) [MBProgressHUD showHUDAddedTo:view animated:YES];
        op = [self POST:path
             parameters:params
                success:^(AFHTTPRequestOperation *operation, id responseObject)
              {
                  if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
                  
                  // call complete block
                  if (block) {
                      block(responseObject);
                  }
              } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
                  NSLog(@"Request Fail: %@", error);
                  // call fail block
                  if (failureBlock) {
                      failureBlock(error);
                  }
              }];
    }
    else if (methodKind == enumAPIRequestMethod_PUT){ // PUT
        if (view) [MBProgressHUD showHUDAddedTo:view animated:YES];
        op = [self PUT:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
            
            // call complete block
            if (block) {
                block(responseObject);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
            NSLog(@"Request Fail: %@", error);
            // call fail block
            if (failureBlock) {
                failureBlock(error);
            }
        }];
    }
    else if(methodKind == enumAPIRequestMethod_POST_ARRAY)
    {
        if (view) [MBProgressHUD showHUDAddedTo:view animated:YES];
        op = [self POST_ARRAY:path parameters:strBody success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
            
            // call complete block
            if (block) {
                block(responseObject);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
            NSLog(@"Request Fail: %@", error);
            // call fail block
            if (failureBlock) {
                failureBlock(error);
            }
        }];
    }
    else { // GET
        if (view) [MBProgressHUD showHUDAddedTo:view animated:YES];
        op = [self GET:path
            parameters:params
               success:^(AFHTTPRequestOperation *operation, id responseObject)
              {
                  if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
                  
                  // call complete block
                  if (block) {
                      block(responseObject);
                  }
              } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
                  NSLog(@"Request Fail: %@", error);
                  // call fail block
                  if (failureBlock) {
                      failureBlock(error);
                  }
              }];
    }
    
    return op;
}















/*
 ## Login
 
 ### Required Parameters: `email` - the user's email
 
 `password` - the user's password
 
 #### Example Request:
 --data "email=demo@demo.com&password=password"  -X POST

 #### Example Response:
 ```javascript
 {
 "success":true,
 "auth_token":"NFW6L8pzzZsYRPCLdvRv",
 "email":"demo@demo.com"
 }

 */
/**************************************************************************************
- (void)requestLoginWithDelegate:(id)delegate
                       requestID:(NSString *)requestID
                           email:(NSString *)strEmail
                         andPass:(NSString *)strPass {
    
    NSDictionary *parameters = @{@"email"       : strEmail,
                                 @"password"    : strPass};
    
    [self.requestManager POST:[self fullURLRequestWithAPI:API_URL_LOGIN]
                   parameters:parameters
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         if ([[responseObject objectForKey:@"success"] boolValue]) {
             if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
                 [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
             }
         } else if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:@"" requestID:requestID];
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}
**************************************************************************************/
/* Membership Request

 ### Required Parameters: `name`, `company`, `phone`, `email`
 
 ### Response :Will either be status OK on success, or an array of missing fields / errors, e.g
 
 ```javascript
 {"errors":["company", "phone", "email"]}
 ```
 
 #### Example Request: curl http://staging.yardclub.com/api/v1/request_membership.json \
 --data "name=luis&company=yardclub&phone=1234567890&email=apitest@example.com"  -X POST
 
 #### Example Response:
 
 ```javascript
 {"status":"OK"}
 
 */
/**************************************************************************************
- (void)requestMembershipWithDelegate:(id)delegate
                            requestID:(NSString *)requestID
                             fullName:(NSString *)strFullName
                                email:(NSString *)strEmail
                          phoneNumber:(NSString *)strPhoneNumber
                              company:(NSString *)strCompany {
    
    NSDictionary *parameters = @{@"name"    : strFullName,
                                 @"company" : strCompany,
                                 @"phone"   : strPhoneNumber,
                                 @"email"   : strEmail};
    
    [self.requestManager POST:[self fullURLRequestWithAPI:API_URL_REQUEST_MEMBERSHIP]
                   parameters:parameters
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
//        NSLog(@"JSON: %@", responseObject);
        if ([[responseObject objectForKey:@"status"] isEqualToString:@"OK"]) {
            if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
                [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        [ApplicationDelegate showNetworkMessageWithAction:@"loading" requestOperation:operation];
        if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
            [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
        }
    }];
    
}
**************************************************************************************/
/**************************************************************************************
- (void)requestActiveRentalsWithDelegate:(id)delegate
                               requestID:(NSString *)requestID
                             authToken:(NSString *)authToken
                                email:(NSString *)strEmail{
    
    NSDictionary *parameters = @{@"auth_token"   : authToken,
                                 @"user_email"   : strEmail};
    
    [self.requestManager GET:[self fullURLRequestWithAPI:API_URL_ACTIVE_RENTAL]
                   parameters:parameters
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         //if ([[responseObject objectForKey:@"status"] isEqualToString:@"OK"]) {
             if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
                 [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
             }
         //}
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         [ApplicationDelegate showNetworkMessageWithAction:@"loading" requestOperation:operation];
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}
**************************************************************************************/
/**************************************************************************************
- (void)requestInternalJobsWithDelegate:(id)delegate
                              requestID:(NSString *)requestID {
    UserObject *userInfo = [NSUserDefaults getUserInfo];
    
    NSDictionary *parameters = @{@"auth_token"   : userInfo.userAccessTooken,
                                 @"user_email"   : userInfo.userEmail};
    
    [self.requestManager GET:[self fullURLRequestWithAPI:API_URL_GET_INTERNAL_JOBS]
                  parameters:parameters
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
             [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         [ApplicationDelegate showNetworkMessageWithAction:@"loading" requestOperation:operation];
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}
**************************************************************************************/
/**************************************************************************************
- (void)requestRentalMessagesWithDelegate:(id)delegate
                                requestID:(NSString *)requestID
                                 rentalId:(int)rentalId {
    
    UserObject *userInfo = [NSUserDefaults getUserInfo];
    NSDictionary *parameters = @{@"auth_token"   : userInfo.userAccessTooken,
                                 @"user_email"   : userInfo.userEmail};
    
    NSString *rentalMessagesAPI = [NSString stringWithFormat:API_URL_RENTAL_MESSAGES_FORMAT, rentalId];
    [self.requestManager GET:[self fullURLRequestWithAPI:rentalMessagesAPI]
                  parameters:parameters
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
             [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}
**************************************************************************************/
/**************************************************************************************
- (void)requestSendMessageWithDelegate:(id)delegate
                             requestID:(NSString *)requestID
                              rentalId:(int)rentalId
                        messageContent:(NSString *)strMessage {
    
    UserObject *userInfo = [NSUserDefaults getUserInfo];
    NSDictionary *parameters = @{@"auth_token"   : userInfo.userAccessTooken,
                                 @"user_email"   : userInfo.userEmail,
                                 @"body"         : strMessage};
    
    NSString *rentalMessagesAPI = [NSString stringWithFormat:API_URL_RENTAL_MESSAGES_FORMAT, rentalId];
    [self.requestManager POST:[self fullURLRequestWithAPI:rentalMessagesAPI]
                  parameters:parameters
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
             [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         [ApplicationDelegate showNetworkMessageWithAction:@"sending message" requestOperation:operation];
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}
**************************************************************************************/
/**************************************************************************************
- (void)requestRentalActionWithDelegate:(id)delegate
                              requestID:(NSString *)requestID
                               rentalId:(int)rentalId {
    
    UserObject *userInfo = [NSUserDefaults getUserInfo];
    NSDictionary *parameters = @{@"auth_token"   : userInfo.userAccessTooken,
                                 @"user_email"   : userInfo.userEmail};
    
    NSString *rentalActionAPI = [NSString stringWithFormat:API_URL_RENTAL_ACTION_FORMAT, rentalId];
    [self.requestManager POST:[self fullURLRequestWithAPI:rentalActionAPI]
                   parameters:parameters
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
             [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         [ApplicationDelegate showNetworkMessageWithAction:@"requesting" requestOperation:operation];
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}
**************************************************************************************/
/**************************************************************************************
- (void)requestExtendRentalWithDelegate:(id)delegate
                              requestID:(NSString *)requestID
                               rentalId:(int)rentalId
                              startDate:(NSDate *)startDate
                                endDate:(NSDate *)endDate {
    
    UserObject *userInfo = [NSUserDefaults getUserInfo];
    NSDictionary *parameters = @{@"auth_token"   : userInfo.userAccessTooken,
                                 @"user_email"   : userInfo.userEmail,
                                 @"start_date"   : [startDate stringDateToRequest],
                                 @"end_date"     : [endDate stringDateToRequest]};
    
    NSString *rentalActionAPI = [NSString stringWithFormat:API_URL_RENTAL_EXTEND_FORMAT, rentalId];
    [self.requestManager POST:[self fullURLRequestWithAPI:rentalActionAPI]
                   parameters:parameters
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
             [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         [ApplicationDelegate showNetworkMessageWithAction:@"requesting" requestOperation:operation];
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}
**************************************************************************************/
/**************************************************************************************
- (void)requestCallOffRentalWithDelegate:(id)delegate
                               requestID:(NSString *)requestID
                                rentalId:(int)rentalId
                                  reason:(NSString *)strReason {
    
    UserObject *userInfo = [NSUserDefaults getUserInfo];
    NSDictionary *parameters = @{@"auth_token"   : userInfo.userAccessTooken,
                                 @"user_email"   : userInfo.userEmail,
                                 @"body"   : strReason};
    
    NSString *rentalActionAPI = [NSString stringWithFormat:API_URL_RENTAL_CALL_OFF_FORMAT, rentalId];
    [self.requestManager POST:[self fullURLRequestWithAPI:rentalActionAPI]
                   parameters:parameters
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
             [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         [ApplicationDelegate showNetworkMessageWithAction:@"requesting" requestOperation:operation];
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}
**************************************************************************************/
/**************************************************************************************
- (void)requestFeaturedItemWithDelegate:(id)delegate
                              requestID:(NSString *)requestID {
    
    [self.requestManager GET:[self fullURLRequestWithAPI:API_URL_FEATURED]
                  parameters:nil
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
             [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         [ApplicationDelegate showNetworkMessageWithAction:@"loading" requestOperation:operation];
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}

- (void)requestUserTotalWithDelegate:(id)delegate
                           requestID:(NSString *)requestID {
    
    UserObject *userInfo = [NSUserDefaults getUserInfo];
    NSDictionary *parameters = @{@"auth_token"   : userInfo.userAccessTooken,
                                 @"user_email"   : userInfo.userEmail};
    
    [self.requestManager GET:[self fullURLRequestWithAPI:API_URL_GET_USER_TOTAL_HOME]
                   parameters:parameters
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
             [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         [ApplicationDelegate showNetworkMessageWithAction:@"requesting" requestOperation:operation];
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}

- (void)requestUserNotificationsWithDelegate:(id)delegate
                                        page:(NSInteger)page
                                   requestID:(NSString *)requestID {
    
    if (page <= 0) page = 1;
    NSNumber *pageNumber = [NSNumber numberWithInt:page];

    UserObject *userInfo = [NSUserDefaults getUserInfo];
    NSDictionary *parameters = @{@"auth_token"   : userInfo.userAccessTooken,
                                 @"user_email"   : userInfo.userEmail,
                                 @"page"         : pageNumber};
    
    [self.requestManager GET:[self fullURLRequestWithAPI:API_URL_GET_USER_NOTIFICATIONS]
                  parameters:parameters
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//         NSLog(@"JSON: %@", responseObject);
         if ([delegate respondsToSelector:@selector(requestSuccessfulWithResponse:requestID:)]) {
             [delegate requestSuccessfulWithResponse:responseObject requestID:requestID];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
         [ApplicationDelegate showNetworkMessageWithAction:@"loading" requestOperation:operation];
         if ([delegate respondsToSelector:@selector(requestFailedWithMessage:requestID:)]) {
             [delegate requestFailedWithMessage:error.localizedDescription requestID:requestID];
         }
     }];
}

- (AFHTTPRequestOperation *)operationWithType:(ENUM_API_REQUEST_TYPE)type andPostMethodKind:(BOOL)methodKind andParams:(NSMutableDictionary *)params inView:(UIView *)view completeBlock:(void (^)(id responseObject))block failureBlock:(void (^)(NSError *error))failureBlock
{
    NSString *path = nil;
    switch (type) {
        case ENUM_API_REQUEST_GET_ACTIVE_RENTALS:
        {
            path = API_URL_ACTIVE_RENTAL;
            break;
        }
        case ENUM_API_REQUEST_ASSIGN_INSPECTION_TO_RENTAL:
        {
            path = [NSString stringWithFormat:API_URL_ASSING_INSPECTIONS_TO_RENTAL, [params[@"active_rental_id"] intValue]];
            [params removeObjectForKey:@"active_rental_id"];
            break;
        }
        case ENUM_API_REQUEST_CREATE_INTERNAL_JOB:
        {
            path = API_URL_CREATE_INTERNAL_JOB;
            break;
        }
        case ENUM_API_REQUEST_ASSIGN_INSPECTION_TO_INTERNAL_JOB:
        {
            path = [NSString stringWithFormat:API_URL_ASSIGN_INSPECTIONS_TO_INTERNAL_JOB, [params[@"active_rental_id"] intValue]];
            [params removeObjectForKey:@"active_rental_id"];
            break;
        }
        case ENUM_API_REQUEST_GET_INTERNAL_JOB_INSPECTIONS:
        {
            path = [NSString stringWithFormat:API_URL_GET_INTERNAL_JOB_INSPECTIONS, [params[@"active_rental_id"] intValue]];
            [params removeObjectForKey:@"active_rental_id"];
            break;
        }
        case ENUM_API_REQUEST_GET_OPEN_REQUESTS:
        {
            path = API_URL_GET_OPEN_REQUESTS;
            break;
        }
        case ENUM_API_REQUEST_DECLINE_OPEN_REQUESTS:
        {
            path = [NSString stringWithFormat:API_URL_DECLINE_OPEN_REQUESTS, params[@"open_request_id"]];
            [params removeObjectForKey:@"open_request_id"];
            break;
        }
        case ENUM_API_REQUEST_OPEN_REQUESTS_GET_EQUIPMENTS:
        {
            path = [NSString stringWithFormat:API_URL_OPEN_REQUESTS_GET_EQUIPMENTS, params[@"open_request_id"]];
            [params removeObjectForKey:@"open_request_id"];
            break;
        }
        case ENUM_API_REQUEST_FULLFILL_OPEN_REQUESTS:
        {
            path = [NSString stringWithFormat:API_URL_FULLFILL_OPEN_REQUESTS, params[@"open_request_id"]];
            [params removeObjectForKey:@"open_request_id"];
            break;
        }
        case ENUM_API_REQUEST_SUBMIT_LIST_EQUIPMENT_REQUEST:
        {
            path = API_URL_SUBMIT_LIST_EQUIPMENT_REQUEST;
            break;
        }
            
        default:
            break;
    }
    if (!path) {
        return nil;
    }
    
    // add token and user email to params
    if (!params) {
        params = [NSMutableDictionary dictionary];
    }
    UserObject *userInfo = [NSUserDefaults getUserInfo];
    [params setObject:userInfo.userAccessTooken forKey:@"auth_token"];
    [params setObject:userInfo.userEmail forKey:@"user_email"];
    
    // get full path
    path = [self fullURLRequestWithAPI:path];
    
    AFHTTPRequestOperation *op;
    if (methodKind) { // POST
        if (view) [MBProgressHUD showHUDAddedTo:view animated:YES];
        op = [self.requestManager POST:path
                           parameters:params
                              success:^(AFHTTPRequestOperation *operation, id responseObject)
              {
                  if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
                  
                  // call complete block
                  if (block) {
                  block(responseObject);
                  }
              } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
                  [ApplicationDelegate showNetworkMessageWithAction:@"loading" requestOperation:operation];
                  // call fail block
                  if (failureBlock) {
                  failureBlock(error);
                  }
              }];
    }
    else { // GET
        if (view) [MBProgressHUD showHUDAddedTo:view animated:YES];
        op = [self.requestManager GET:path
                      parameters:params
                         success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
             
             // call complete block
             if (block) {
             block(responseObject);
             }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             if (view) [MBProgressHUD hideAllHUDsForView:view animated:YES];
             [ApplicationDelegate showNetworkMessageWithAction:@"loading" requestOperation:operation];
             // call fail block
             if (failureBlock) {
             failureBlock(error);
             }
         }];
    }
    return op;
}

-(AFHTTPRequestOperation *)operationMultiPartWithType:(ENUM_API_REQUEST_TYPE)type andParams:(NSMutableDictionary *)params withValues:(NSArray *)values andKeys:(NSArray *)keys inView:(UIView *)view progressBlock:(WebserviceManagerUploadProgressBlock)progressBlock completeBlock:(WebserviceManagerCompleteBlock)completeBlock failureBlock:(WebserviceManagerFailureBlock)failureBlock
{
    // path
    NSString *path = nil;
    switch (type) {
        case ENUM_API_REQUEST_UPLOAD_INSPECTION_TO_RENTAL:
        {
            path = [NSString stringWithFormat:API_URL_INSPECTION_UPLOAD_PHOTO, [params[@"active_rental_id"] intValue]];
            [params removeObjectForKey:@"active_rental_id"];
            break;
        }
        case ENUM_API_REQUEST_UPLOAD_INSPECTION_TO_INTERNAL_JOB:
        {
            path = [NSString stringWithFormat:API_URL_INSPECTION_UPLOAD_INTERNAL_JOB, [params[@"active_rental_id"] intValue]];
            [params removeObjectForKey:@"active_rental_id"];
            break;
        }
        case ENUM_API_REQUEST_UPLOAD_INSPECTION_WITHOUT_RENTAL:
        {
            path = API_URL_UPLOAD_INSPECTION_PHOTO_WITHOUT_RENTAL;
            break;
        }
        default:
            break;
    }
    if (!path) {
        return nil;
    }
    
    path = [[WebserviceManager sharedInstance] fullURLRequestWithAPI:path];
    // params
    UserObject *userInfo = [NSUserDefaults getUserInfo];
    [params setObject:userInfo.userAccessTooken forKey:@"auth_token"];
    [params setObject:userInfo.userEmail forKey:@"user_email"];

    if (view) [MBProgressHUD showHUDAddedTo:view animated:YES];
    AFHTTPRequestOperation *op = [self.requestManager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // append data
        for (int i = 0; i < values.count; i++) {
            id object = [values objectAtIndex:i];
            id key = [keys objectAtIndex:i];
            if ([object isKindOfClass:[NSData class]]) {
                [formData appendPartWithFileData:object name:key fileName:@"photo.jpg" mimeType:@"image/jpg"];
            }
            else {
                if ([object respondsToSelector:@selector(dataUsingEncoding:)]) {
                    [formData appendPartWithFormData:[object dataUsingEncoding:NSUTF8StringEncoding] name:key];
                } else if ([object isKindOfClass:[NSNumber class]]) {
                    [formData appendPartWithFormData:[[object stringValue] dataUsingEncoding:NSUTF8StringEncoding] name:[keys objectAtIndex:i]];
                }
            }
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (view) [MBProgressHUD hideHUDForView:view animated:YES];
        
        // call complete block
        if (completeBlock) {
            completeBlock(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (view) [MBProgressHUD hideHUDForView:view animated:YES];
        [ApplicationDelegate showNetworkMessageWithAction:@"loading" requestOperation:operation];
        // call fail block
        if (failureBlock) {
            failureBlock(error);
        }
    }];
    
    // add progress block
    if (progressBlock) {
        [op setUploadProgressBlock:^(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
            progressBlock(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
        }];
    }
    // start operation
    [op start];
    
    return op;
}
**************************************************************************************/
@end
